#!/usr/bin/env python
import quark
import tkinter as tk
import os
import requests

#百度翻译
class transtion():

    def get_url(self,word):
        if self.is_chinese(word):
            url = 'https://fanyi.baidu.com/v2transapi?from=zh&to=en'
        else:
            url = 'https://fanyi.baidu.com/v2transapi?from=en&to=zh'
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36 Edg/96.0.1054.43',
            'Referer': 'https://fanyi.baidu.com/',
            'cookie': ''#添加自己的cookie
        }
        #需安装nodejs
        #打开nodejs运行js，获取sign，直接调用python的execjs库运行在长文章翻译时会结果错误
        #输出的sign带了‘\n’，用替换语句把它去掉
        sign = os.popen(f'node.exe D:\pythonProject\百度翻译加密.js "{word}"').readlines()[0].replace('\n','')

        data_1 = {
            'from': 'en',
            'to': 'zh',
            'query': word,
            'simple_means_flag': '3',
            'sign': sign,
            'token': '570ee6a57481da2c6f073050611487f4',
            'domain': 'common'
        }
        data_2 = {
            'from': 'zh',
            'to': 'en',
            'query': word,
            'simple_means_flag': '3',
            'sign': sign,
            'token': '570ee6a57481da2c6f073050611487f4',
            'domain': 'common'
        }
        #判断翻译方式,发送相应data
        if self.is_chinese(word) or word.isdigit():
            data = data_2

        else:
            data = data_1
        #print(data)
        res = requests.post(url,headers=headers,data=data)

        means = res.json()

        #单词英翻中，获取多个词义
        try:
            #设置报错条件，让某些情形报错从而执行另外的语句
            test = means['dict_result']['simple_means']['symbols'][0]['parts'][0]['part']
            return means['dict_result']['simple_means']['symbols'][0]['parts']
        #其他情况如中翻英、单词含其他符号、句子等直接翻译
        except KeyError:
            return means['trans_result']['data'][0]['dst']
    #判断是否含中文字符
    def is_chinese(self,char):
        if char >= '\u4e00' and char <= '\u9fa5':
                return True
        else:
                return False

    def main(self,word):


        #判断是否为空
        if word =='' or word.isspace() :
            return ''

        return self.get_url(word)


#ui界面
class ui(transtion):
    def __init__(self):

        self.root = tk.Tk()
        self.root.title('简陋翻译')
        self.root.geometry('780x380')

        self.w = tk.Entry(self.root,bd=2,width=20)
        self.w.place(x=90,y=100)

        self.title1 = tk.Label(self.root, text='翻译内容')
        self.title1.place(x=90, y=70)
        self.title2 = tk.Label(self.root,text='翻译结果')
        self.title2.place(x=290,y=70)

        b1 = tk.Button(self.root, text='翻译', bd=1, width=10, command=self.submit)
        b1.place(x=90, y=150)

        self.text = tk.Text(self.root,width=40,height=10,font='宋体')
        self.text.place(x=290,y=100)

        #设置翻译接口判断初始值
        self.select=2
        #定义单选框的分配变量
        self.var = tk.IntVar()
        #设置单选框分配变量，让其初始化不选，当value=variable，则默认选择
        self.var.set(2)
        C1 = tk.Radiobutton(self.root, text="baidu",variable=self.var,value=1,command=self.select0)
        C2 = tk.Radiobutton(self.root, text="quark",variable=self.var,value=0,command=self.select1)

        C1.grid(row=0,column=0)
        C2.grid(row=0,column=1)
    #判断选择接口函数
    def select0(self):
        self.select=0
        return self.select
    def select1(self):
        self.select=1
        return self.select

    def submit(self):
        #获取文字框输入
        word = self.w.get()

        #判断接口
        if self.select==0:
            result = self.main(word)
            # print(type(result))
            self.text.delete(1.0, tk.END)
            long = len(result)
            #输出多词义
            try:
                for i in range(long):
                    self.text.insert(tk.END, result[i]['part']+' ')
                    self.text.insert(tk.END,result[i]['means'])
                    self.text.insert(tk.INSERT, '\n')
            #其他情况
            except:
                self.text.insert(tk.END, result)
        elif self.select==1:
            self.text.delete(1.0, tk.END)
            result = quark.main1(word)
            long = len(result)
            #最后的同义词直接获取text会输出一整串英文，所以需要判断处理
            for i in range(long):
                self.text.insert(tk.END, result[i].text)
                self.text.insert(tk.INSERT, '\n')
                if result[i].text == '同义词':
                    x = 1
                    for a in range(i+1,long):
                        if x % 2 == 0:
                            for string in result[a].strings:
                                self.text.insert(tk.END, string+'; ')
                            self.text.insert(tk.INSERT, '\n')
                        else:
                            self.text.insert(tk.END, result[a].text)
                            self.text.insert(tk.INSERT, '\n')
                        x+=1
                    break




    def run(self):
        self.root.mainloop()
if __name__ == '__main__':

    exe = ui()
    exe.run()


